<template>
  <div class="boxs">
    <div class="flex-box">
      <div class="top">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
      >
        <el-form-item label="" prop="name">
          <el-input
              v-model="queryParams.query"
              placeholder="请输入订单名称"
              clearable
              @input="handleQuery"
          />
        </el-form-item>
      </el-form>
      </div>
      
      <div>
        <el-button icon="el-icon-plus" type="primary"  size="small" @click="openDialog">添加订单</el-button>
         <el-button type="danger" size="small" @click="handleBatchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
      </div>
    </div>
    <el-table :data="OrderArr" style="width: 100%" v-loading="loading" 
    ref="orderTable"
    row-key="id"
    @selection-change="handleSelectionChange">
      <!-- <el-table-column label="订单编号" align="center" prop="id" min-width="80">
        <template slot-scope="scope">
          {{ scope.row.orderId}}
        </template> 
      </el-table-column> -->
       <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column label="订单名称" align="center" prop="name" min-width="100">
        <template slot-scope="scope">
          {{scope.row.orderName}}
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName" min-width="100">
        <template slot-scope="scope">
          {{scope.row.customerName}}
        </template>
      </el-table-column>
       
       <el-table-column label="状态" align="center" prop="state" min-width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.state==1?'':scope.row.state==2?'success':scope.row.state==3?'warning':scope.row.state==4?'danger':'info'"
            effect="dark">
            {{ scope.row.state==1?'进行中':scope.row.state==2?'已完成':scope.row.state==3?'已回款':scope.row.state==4?'已发工资':'-'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="update_time" min-width="180" :formatter="formatterCreateTime" />
      <el-table-column label="完成时间" align="center" prop="finishTime" min-width="180" :formatter="formatterFinishTime" />
      <el-table-column label="备注" align="center" prop="remark" min-width="100">
        <template slot-scope="scope">
          {{scope.row.remark}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini"  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini"  type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getOrder"
    />
    <el-dialog title="订单信息" :visible.sync="dialogVisible" width="60%"  :close-on-click-modal="false">
      <el-form class="demo-form-inline" label-width="80px" :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入订单名称" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择" @change="customerChange">
            <el-option
              v-for="item in customers"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工序列表" prop="name">
          <el-button size="small" type="primary" @click="addProcess">添加工序</el-button>
        </el-form-item>
        <div v-for="(process,index) in form.processArry" v-bind:key="index" style="padding:10px 0px;display:flex;align-items: center;">
          <div style="font-size:24px;flex:0 0 80px;padding-right:12px;text-align:center;color:red;cursor:pointer" @click="delProcess(index)" >
            <i class="el-icon-delete" v-if="form.processArry.length>1"></i>
          </div>
          <div>
              <el-descriptions class="margin-top" title="" :column="1" size="medium" border >
              <el-descriptions-item>
                <template slot="label">
                  工序
                </template>
                <el-select v-model="process.processId" placeholder="工序" style="width:100px;margin-right:10px" @change="processChange(index)">
                      <el-option
                        v-for="item in processes"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <el-select v-model="process.unitId" placeholder="单位" style="width:100px;margin-right:10px" @change="unitChange(index)">
                      <el-option
                        v-for="item in units"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <el-input v-model="process.customerprice" placeholder="客户单价"  style="width:100px;"/>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  工人
                </template>
                    <div style="margin-bottom:10px">
                      <el-button size="mini" type="primary" @click="addWorker(index)">添加工人</el-button>
                    </div>
                    <div v-for="(worker,i) in process.workers" v-bind:key="i" style="margin-bottom:10px">
                      <el-select v-model="worker.workerId"  placeholder="工人"  style="width:100px;margin-right:10px" @change="workerChange(index,i)">
                        <el-option
                          v-for="item in workers"
                          :key="item.id"
                          :label="item.username"
                          :value="item.id">
                        </el-option>
                      </el-select>
                      
                      <el-input v-model="worker.workerprice" placeholder="工人单价"  style="width:100px;margin-right:10px"/>
                      <el-input v-model="worker.number" placeholder="数量" style="width:100px"/>
                      <i class="el-icon-delete" style="padding:0px 20px;font-size:16px;color:red;cursor:pointer" @click="delWorker(index,i)" v-if="process.workers.length>1"></i>
                    </div>
              </el-descriptions-item>
              </el-descriptions>
          </div>
        </div>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio :label="1">进行中</el-radio>
            <el-radio :label="2">已完成</el-radio>
            <el-radio :label="3">已回款</el-radio>
            <el-radio :label="4">已发工资</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
              type="textarea"
              placeholder="请输入备注"
              v-model="form.remark"
              :autosize="{ minRows: 4, maxRows: 4}"
            >
            </el-input>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer" v-loading="addLoading">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="form.id ? 'warning' : 'primary'" @click="affirm">{{
            form.id ? "确认修改" : "确认添加"
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getCustomer,getProcesses,getWorker,getUnit,getOrder, addOrder, upOrder, delOrder,getOrderById,getProcessByProcessIds,getWorkerByWorkerIds,addOrderForWorker,addOrderForProcess,delOrderForProcess,delOrderForWorker,delOrderForWorkerById,upOrderForWorker,delToOrder,upOrderForProcess,migrateWorkerNumberRecords} from '@/api/admin';
import {formatDate,getOrderNo} from "@/utils";
export default {
  name:"Order",
  data () {
    return {
      selectedIds: [], 
      queryParams:{
        page:1,
        size:10
      },
      customers:[],
      processes:[],
      units:[],
      workers:[],
      total:0,
      loading:false,
      addLoading:false,
      OrderArr: [],
      dialogVisible: false,
      rolesArr: [],
      moreArr: [],
      search: '',
      form: {
        orderName:'',
        customerId:'',
        customerName:'',
        processArry:[
          {
            processId:'',
            processName:'',
            unitId:'',
            unitName:'',
            customerprice:'',
            workers:[
              {
                workerId:'',
                workerName:'',
                workerprice:'',
                number:'',
              }
            ],

          }
        ],
        state:1,
        remark:''
      },
      rules: {
        orderName: [
          { required: true, message: '请输入订单名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' },
        ],
      },
    }
  },
  async created () {
    this.getOrder()
    this.getCustomer();
      this.getWorker();
      this.getProcesses();
      this.getUnit();
  },
  methods: {
    handleSelectionChange(selection) {
      // 提取当前页选中的ID
      const currentPageIds = selection.map(row => row.id);
      
      // 找出需要添加和需要移除的ID
      const addIds = currentPageIds.filter(id => !this.selectedIds.includes(id));
      const removeIds = this.selectedIds.filter(id => !currentPageIds.includes(id));
      
      // 更新选中ID数组
      this.selectedIds = [...this.selectedIds.filter(id => !removeIds.includes(id)), ...addIds];
    },
    
    // 修改批量删除方法
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的订单');
        return;
      }
      
      this.$confirm(`确定要删除选中的 ${this.selectedIds.length} 条订单吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        try {
          // 调用批量删除接口（如果后端支持）
          await delToOrder({ ids: this.selectedIds });
          
          // 清空选中状态
          this.selectedIds = [];
          this.$refs.orderTable.clearSelection();
          
          // 重新获取订单列表
          this.getOrder();
          this.$message.success('批量删除成功！');
        } catch (error) {
          this.$message.error('删除失败，请重试');
        }
      });
    },
    //修改
    customerChange(){
      this.form.customerName=this.customers.find(item => item.id === this.form.customerId).username;
    },
    unitChange(index){
      this.form.processArry[index].unitName=this.units.find(item => item.id === this.form.processArry[index].unitId).name;
    },
    processChange(index){
      this.form.processArry[index].processName=this.processes.find(item => item.id === this.form.processArry[index].processId).name;
    },
    workerChange(index,i){
      this.form.processArry[index].workers[i].workerName=this.workers.find(item => item.id === this.form.processArry[index].workers[i].workerId).username;
      this.form.processArry[index].workers[i].phone=this.workers.find(item => item.id === this.form.processArry[index].workers[i].workerId).phone;
    },

    addProcess(){
       this.form.processArry.push({
            processId:'',
            processName:'',
            unitId:'',
            unitName:'',
            customerprice:'',
            workers:[
              {
                workerId:'',
                workerName:'',
                workerprice:'',
                number:'',
              }
            ],

          })
    },
    delProcess(index){
      alert(index)
      console.log(this.form.processArry);
       this.form.processArry.splice(index, 1);
    },
    addWorker(i){
       this.form.processArry[i].workers.push({
                workerId:'',
                workerName:'',
                workerprice:'',
                number:'',
              })
    },
    delWorker(index,i){
      this.form.processArry[index].workers.splice(i, 1);
    },

    //获取工人列表
    async getCustomer(){
      const {data,total} = await getCustomer();
      this.customers=data;
    },
    async getProcesses(){
      const {data,total} = await getProcesses();
      this.processes=data;
    },
    async getWorker(){
      const {data,total} = await getWorker();
      this.workers=data;
    },
    async getUnit(){
      const {data,total} = await getUnit();
      this.units=data;
    },
    formatterCreateTime(row){
      return formatDate(row.update_time);
    },
    formatterFinishTime(row){
      return formatDate(row.finishTime);
    },

    handleDelete (id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await delOrder({ id: id });
        this.getOrder();
        this.$message({
          message: '删除成功！',
          type: 'success'
        });
      })
    },
    resetForm () {
      this.form= {
        orderId:'',
        orderName:'',
        customerId:'',
        customerName:'',
        processArry:[
          {
            processId:'',
            processName:'',
            unitId:'',
            unitName:'',
            customerprice:'',
            workers:[
              {
                phone:'',
                workerId:'',
                workerName:'',
                workerprice:'',
                number:'',
              }
            ],

          }
        ],
        state:1,
        remark:''
      }
    },
    async handleEdit (index, row) {
      this.resetForm();
      let result1 = await getOrderById({
        id:row.id
      });
      let result2 = await getProcessByProcessIds({
        orderId:row.orderId
      });
      result1.data.processArry=result2.data;
      console.log(99999,result1.data)
      this.form=Object.assign({}, this.form, result1.data);
      this.$set(this.form, 'processArry', result2.data);
      for (const p of this.form.processArry) {
          const result3 =await getWorkerByWorkerIds({
            orderProcessId:p.orderProcessId
          });
          this.$set(p, 'workers', result3.data);
      }
      console.log(1,this.form.processArry);
      this.dialogVisible = true;
    },
    validateOrderData(orderData) {
      const errors = [];
      if (!orderData.processArry || !Array.isArray(orderData.processArry)) {
        errors.push('工序数据格式错误');
        return { isValid: false, errors };
      }
      
      if (orderData.processArry.length === 0) {
        errors.push('至少需要添加一个工序');
      }
      
      // 3. 遍历验证每个工序
      orderData.processArry.forEach((process, index) => {
        const processPrefix = `工序 ${index + 1}: `;
        
        if (!process.processName?.trim()) {
          errors.push(`${processPrefix}工序名称不能为空`);
        }
        
        
        if (!process.unitName?.trim()) {
          errors.push(`${processPrefix}单位名称不能为空`);
        }
        
        if (!process.customerprice) {
          errors.push(`${processPrefix}客户价格不能为空`);
        } else if (isNaN(parseFloat(process.customerprice))) {
          errors.push(`${processPrefix}客户价格必须是有效数字`);
        }
        
        // 4. 验证工人数组
        if (!process.workers || !Array.isArray(process.workers)) {
          errors.push(`${processPrefix}工人数据格式错误`);
          return;
        }
        
        if (process.workers.length === 0) {
          errors.push(`${processPrefix}至少需要添加一个工人`);
        }
        
        // 5. 遍历验证每个工人
        process.workers.forEach((worker, workerIndex) => {
          const workerPrefix = `${processPrefix}工人 ${workerIndex + 1}: `;
          

          if (!worker.workerName?.trim()) {
            errors.push(`${workerPrefix}工人名称不能为空`);
          }
          
          if (!worker.workerprice) {
            errors.push(`${workerPrefix}工人价格不能为空`);
          } else if (isNaN(parseFloat(worker.workerprice))) {
            errors.push(`${workerPrefix}工人价格必须是有效数字`);
          }
          
          if (!worker.number) {
            errors.push(`${workerPrefix}数量不能为空`);
          } else if (isNaN(parseInt(worker.number)) || parseInt(worker.number) <= 0) {
            errors.push(`${workerPrefix}数量必须是大于0的整数`);
          }
        });
      });
      
      return {
        isValid: errors.length === 0,
        errors
      };
    },
    async affirm () {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (!valid) return;
        const vaildFlag=this.validateOrderData(this.form);
        if(!vaildFlag.isValid){
          this.$message.error('请提交完整信息');
        }else{
          try {
            this.addLoading=true;
            let orderId='';
            if(this.form.id){
              orderId=this.form.orderId
              console.log(orderId)
              // 保存原有工序完整信息（包括工序和工人），用于智能匹配和数据迁移
              const originalProcesses = await getProcessByProcessIds({
                orderId:orderId
              });
              
              // 为每个原有工序获取其关联的工人信息
              this.originalProcessFullMap = {};
              for (const process of originalProcesses.data) {
                const workers = await getWorkerByWorkerIds({
                  orderProcessId: process.orderProcessId
                });
                this.originalProcessFullMap[process.orderProcessId] = {
                  processId: process.processId,
                  orderProcessId: process.orderProcessId,
                  workerIds: workers.data.map(w => w.workerId).sort()
                };
              }

            }else{
              orderId=getOrderNo("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10;
            }
            
            // 智能匹配函数：通过工序类型和工人ID来匹配原有工序
            const findMatchingOriginalProcess = (currentProcess) => {
              if (!this.originalProcessFullMap) return null;
              
              const currentWorkerIds = currentProcess.workers.map(w => w.workerId).sort();
              
              // 优先匹配：工序类型相同且工人ID完全相同
              for (const [orderProcessId, originalProcess] of Object.entries(this.originalProcessFullMap)) {
                if (originalProcess.processId == currentProcess.processId && 
                    JSON.stringify(originalProcess.workerIds) === JSON.stringify(currentWorkerIds)) {
                  return orderProcessId;
                }
              }
              
              // 次优匹配：工人ID有交集（至少有一个工人相同）
              for (const [orderProcessId, originalProcess] of Object.entries(this.originalProcessFullMap)) {
                const hasCommonWorker = originalProcess.workerIds.some(workerId => currentWorkerIds.includes(workerId));
                if (hasCommonWorker) {
                  return orderProcessId;
                }
              }
              
              // 最后匹配：只匹配工序类型（如果当前没有工人）
              if (currentWorkerIds.length === 0) {
                for (const [orderProcessId, originalProcess] of Object.entries(this.originalProcessFullMap)) {
                  if (originalProcess.processId == currentProcess.processId) {
                    return orderProcessId;
                  }
                }
              }
              
              return null;
            };
            
            // 记录已使用的原有工序ID，避免重复使用
            const usedOrderProcessIds = new Set();
            
            // 如果是编辑模式，先删除不再需要的工序
            if(this.form.id && this.originalProcessFullMap) {
              // 先尝试为每个新工序匹配原有工序
              const matchedOrderProcessIds = new Set();
              for (const p of this.form.processArry) {
                const matchedId = findMatchingOriginalProcess(p);
                if (matchedId) {
                  matchedOrderProcessIds.add(matchedId);
                }
              }
              
              // 删除未被匹配的原有工序
              for (const [orderProcessId, originalProcess] of Object.entries(this.originalProcessFullMap)) {
                if (!matchedOrderProcessIds.has(orderProcessId)) {
                  await delOrderForProcess({ orderId: orderId, orderProcessId: orderProcessId });
                }
              }
            }
            
            for (const p of this.form.processArry) {
              let orderProcessId;
              let isNewProcess = false;
              
              // 智能匹配原有工序
              const matchedOrderProcessId = this.form.id ? findMatchingOriginalProcess(p) : null;
              
              if (matchedOrderProcessId && !usedOrderProcessIds.has(matchedOrderProcessId)) {
                orderProcessId = matchedOrderProcessId;
                usedOrderProcessIds.add(orderProcessId);
                // 更新工序信息
                await upOrderForProcess({
                  orderProcessId: orderProcessId,
                  processId: p.processId,
                  processName: p.processName,
                  unitId: p.unitId,
                  unitName: p.unitName,
                  customerprice: p.customerprice,
                });
              } else {
                orderProcessId = getOrderNo("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10;
                isNewProcess = true;
                // 如果匹配到了已使用的旧工序，说明是重复的工序，需要迁移工人数量记录
                if (matchedOrderProcessId && usedOrderProcessIds.has(matchedOrderProcessId)) {
                  // 迁移旧的工人数量记录到新的orderProcessId
                  await migrateWorkerNumberRecords({
                    oldOrderProcessId: matchedOrderProcessId,
                    newOrderProcessId: orderProcessId
                  });
                } else if (matchedOrderProcessId && !usedOrderProcessIds.has(matchedOrderProcessId)) {
                  // 匹配到了旧工序但未使用（可能是因为其他原因创建新工序），也要迁移数据
                  await migrateWorkerNumberRecords({
                    oldOrderProcessId: matchedOrderProcessId,
                    newOrderProcessId: orderProcessId
                  });
                } else if (this.originalProcessFullMap) {
                  // 即使没有完全匹配，也要检查是否有部分匹配的工序（通过工人ID）
                  const currentWorkerIds = p.workers.map(w => w.workerId).sort();
                  let bestMatchOrderProcessId = null;
                  let maxCommonWorkers = 0;
                  
                  for (const [opId, originalProcess] of Object.entries(this.originalProcessFullMap)) {
                    if (usedOrderProcessIds.has(opId)) continue;
                    
                    const commonWorkers = originalProcess.workerIds.filter(wid => 
                      currentWorkerIds.includes(wid)
                    ).length;
                    
                    if (commonWorkers > maxCommonWorkers) {
                      maxCommonWorkers = commonWorkers;
                      bestMatchOrderProcessId = opId;
                    }
                  }
                  
                  // 如果有部分匹配且至少有1个共同工人，迁移数据
                  if (bestMatchOrderProcessId && maxCommonWorkers > 0) {
                    await migrateWorkerNumberRecords({
                      oldOrderProcessId: bestMatchOrderProcessId,
                      newOrderProcessId: orderProcessId
                    });
                  }
                }
                // 新增工序
                await addOrderForProcess({
                  orderProcessId:orderProcessId,
                  orderId:orderId,
                  processId: p.processId,
                  processName: p.processName,
                  unitId: p.unitId,
                  unitName: p.unitName,
                  customerprice: p.customerprice,
                });
              }
              
              // 处理工人信息：增量更新，避免丢失工人数量记录
              if(this.form.id && !isNewProcess) {
                // 编辑模式且是匹配的原有工序：增量更新工人
                // 获取原有工人列表
                const originalWorkers = await getWorkerByWorkerIds({
                  orderProcessId: orderProcessId
                });
                const originalWorkerMap = {};
                originalWorkers.data.forEach(worker => {
                  originalWorkerMap[worker.workerId] = worker;
                });
                
                // 找出需要删除和新增的工人
                const currentWorkerIds = p.workers.map(w => w.workerId);
                const originalWorkerIds = Object.keys(originalWorkerMap).map(id => id.toString());
                
                // 删除不再需要的工人（只删除工人记录，不删除数量记录）
                for (const workerId of originalWorkerIds) {
                  if (!currentWorkerIds.includes(workerId)) {
                    // 只删除该工人的记录
                    await delOrderForWorkerById({
                      orderProcessId: orderProcessId,
                      workerId: workerId
                    });
                  }
                }
                
                // 添加或更新工人
                await Promise.all(
                  p.workers.map(async (w) => {
                    if (originalWorkerMap[w.workerId]) {
                      // 工人已存在，更新信息（保留realNumber）
                      const originalWorker = originalWorkerMap[w.workerId];
                      await upOrderForWorker({
                        id: originalWorker.id,
                        orderProcessId: orderProcessId,
                        workerId: w.workerId,
                        workerName: w.workerName,
                        phone: w.phone,
                        workerprice: w.workerprice,
                        number: w.number,
                        realNumber: originalWorker.realNumber || w.realNumber || 0, // 保留原有的realNumber
                      });
                    } else {
                      // 新工人，添加记录
                      const result = await addOrderForWorker({
                        orderProcessId: orderProcessId,
                        workerId: w.workerId,
                        workerName: w.workerName,
                        phone: w.phone,
                        workerprice: w.workerprice,
                        number: w.number,
                        realNumber: w.realNumber || 0,
                      });
                      return result.data;
                    }
                  })
                );
              } else {
                // 新工序或新增的工序：直接添加所有工人
                await Promise.all(
                  p.workers.map(async (w) => {
                    const result = await addOrderForWorker({
                      orderProcessId:orderProcessId,
                      workerId:w.workerId,
                      workerName:w.workerName,
                      phone:w.phone,
                      workerprice:w.workerprice, 
                      number:w.number, 
                      realNumber:w.realNumber || 0,
                    });
                    return result.data;
                  })
                );
              }
            }
            !this.form.id&& await addOrder({
              orderId:orderId,
              orderName:this.form.orderName, 
              customerId:this.form.customerId, 
              customerName:this.form.customerName, 
              remark:this.form.remark, 
            });
            this.form.id&& await upOrder(
              {
                id:this.form.id,
                state:this.form.state,
                orderName:this.form.orderName, 
                customerId:this.form.customerId, 
                customerName:this.form.customerName, 
                remark:this.form.remark, 
              }
            );
            this.addLoading=false;
            this.$message.success(this.form.id?'修改成功！':'添加成功！');
            this.getOrder();
            this.dialogVisible = false;
          }catch (e) {
            this.addLoading=false;
            console.error('订单操作失败:', e);
            if (e.response && e.response.data && e.response.data.msg) {
              this.$message.error(e.response.data.msg);
            } else {
              this.$message.error('操作失败，请重试');
            }
          }
        }

      });
    },
    openDialog () {
      this.resetForm();
      this.dialogVisible = true
    },
    async getOrder () {
      this.loading=true;
      const {data,total} = await getOrder(this.queryParams);
      this.loading=false;
      this.OrderArr = data;
      this.total=total;
       // 重新设置选中状态
      this.OrderArr.forEach(row => {
        if (this.selectedIds.includes(row.id)) {
          this.$refs.orderTable.toggleRowSelection(row, true);
        }
      });
    },
    handleQuery(){
      this.queryParams.page=1;
      this.getOrder();
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-card__header{
    padding: 0;
}
.top .el-form-item{
  margin-bottom: 0;
}
.boxs {
  padding: 20px;
}
.flex-box{
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.color-title{
  margin-bottom: 10px;
  color: #000;
}
</style>
